package endpoint

import (
	"addsvc"
	"context"
	"errors"

	"github.com/go-kit/kit/endpoint"
)

func New(srv addsvc.Service) *Endpoints {
	sum := makeSumEndpoint(srv)

	concat := makeConcatEndpoint(srv)

	return &Endpoints{
		sum,
		concat,
	}
}

type Endpoints struct {
	SumPoint    endpoint.Endpoint
	ConcatPoint endpoint.Endpoint
}

func (e *Endpoints) Sum(ctx context.Context, a, b int) (int, error) {

	request := SumRequest{A: a, B: b}
	response, err := e.SumPoint(ctx, request)
	if err != nil {
		return 0, err
	}
	resp := response.(SumResponse)
	return resp.V, resp.Err
}

func (e *Endpoints) Concat(ctx context.Context, a, b string) (string, error) {
	request := ConcatRequest{A: a, B: b}
	response, err := e.ConcatPoint(ctx, request)
	if err != nil {
		return "", err
	}
	resp := response.(ConcatResponse)
	return resp.V, resp.Err
}

var ErrInvalidRequest = errors.New("invalid request")

func makeSumEndpoint(s addsvc.Service) endpoint.Endpoint {
	return func(ctx context.Context, request any) (any, error) {
		req, ok := request.(SumRequest)
		if !ok {
			return nil, ErrInvalidRequest
		}
		v, err := s.Sum(ctx, req.A, req.B)
		return SumResponse{V: v, Err: err}, nil
	}
}
func makeConcatEndpoint(s addsvc.Service) endpoint.Endpoint {
	return func(ctx context.Context, request any) (any, error) {
		req, ok := request.(ConcatRequest)
		if !ok {
			return nil, ErrInvalidRequest
		}
		v, err := s.Concat(ctx, req.A, req.B)
		return ConcatResponse{V: v, Err: err}, nil
	}
}
